﻿#include <QDebug>
#include <QJsonDocument>
#include "Crypto.h"

Crypto::Crypto(const QString &key) : key(key.toUtf8()) {}

QByteArray Crypto::applyXor(const QByteArray &data)
{
    QByteArray result = data;
    int keyLen = key.size();
    for (int i = 0; i < data.size(); ++i) {
        result[i] = data[i] ^ key[i % keyLen];
    }
    return result;
}

QString Crypto::encrypt(const QString &plainText)
{
    QByteArray encrypted = applyXor(plainText.toUtf8());
    return QString(encrypted.toBase64());
}

QString Crypto::decrypt(const QString &cipherText)
{
    QByteArray encryptedData = QByteArray::fromBase64(cipherText.toUtf8());
    QByteArray decrypted = applyXor(encryptedData);
    return QString::fromUtf8(decrypted);
}

bool Crypto::isEncrypted(const QString &text)
{
    QByteArray byteArray = QByteArray::fromBase64(text.toUtf8());

    if (byteArray.isEmpty()) {
        return false;
    }
    QJsonDocument jsonDoc = QJsonDocument::fromJson(text.toUtf8());
    if (jsonDoc.isNull()) {
         return true;
    }
    else {
        return false;
    }
}

